#!/bin/bash

statustaosd(){
  # ftaosstatus=`sudo systemctl status taosd | grep -E '^\s+Active:' | awk -F '[: ]+' '{print $3}'`
  ftaosstatus=`sudo systemctl is-active taosd`
  if [[ "$ftaosstatus" == "active" ]]
  then
    echo "active"
  fi
  ftaosstatus=`sudo docker inspect --format '{{.State.Running}}' tdengine 2>/dev/null`
  if [[ "$ftaosstatus" == "true" ]]
  then
    echo "active"
  fi
}
stoptaosd(){
  ftaosstatus=`sudo systemctl is-active taosd`
  if [[ "$ftaosstatus" == "active" ]]
  then
    timeout 30s sudo systemctl stop taosd 
    taosd_pid=`ps -ef | grep "/usr/bin/taosd" | grep -v grep | awk '{print $2}'`
    if [[ ! -z ${taosd_pid} ]]
    then
      sudo xargs kill -9 $taosd_pid
    fi
  fi
  ftaosstatus=`sudo docker inspect --format '{{.State.Running}}' tdengine 2>/dev/null`
  if [[ "$ftaosstatus" == "true" ]]
  then
    sudo docker stop tdengine
  fi
}
restarttaosd(){
  ftaosstatus=`sudo systemctl is-active taosd`
  if [[ "$ftaosstatus" == "active" ]]
  then
    echo "restart taosd by systemd.. ."
    sudo systemctl restart taosd 
    return
  fi
  sudo docker ps -a | grep tdengine
  if [[ $? -eq 1 ]]
  then
    echo "restart taosd by systemd... .. ."
    sudo systemctl restart taosd
    return
  fi
  echo "restart taosd by docker... .. ."
  sudo docker restart tdengine
}
stoptaosadapter(){
  ftaosstatus=`sudo systemctl is-active taosd`
  if [[ "$ftaosstatus" == "active" ]]
  then
    timeout 30s sudo systemctl stop taosadapter 
    taosd_pid=`ps -ef | grep "taosadapter" | grep -v grep | awk '{print $2}'`
    if [[ ! -z ${taosd_pid} ]]
    then
      sudo xargs kill -9 $taosd_pid
    fi
  fi
}
restarttaosadapter(){
  ftaosstatus=`sudo systemctl is-active taosd`
  if [[ "$ftaosstatus" == "active" ]]
  then
    sudo systemctl restart taosadapter 
  fi
}
check_switch_version_status(){
  taos -hlocalhost -s "create user yapai pass 'ypkj@1234'"
  if [[ "$ROLL_BACK" == "false" ]]
  then
    sleep 15
    sh ${SYSTEM_INIT_FOLDER}/05_db_create_taos.sh
    # import to new taosd
    sudo taosdump -c /etc/taos/taos.cfg -i ${HOME}/temp/taos/${ENCRY_NAME}/data -h${REMOTE_SERVER} -uyapai -pypkj@1234 -T8
  else
    echo "copy old taos data... .. ."
    sudo rm -rf /var/lib/taos/*
    sudo tar -zxvf ${HOME}/temp/taos/${ENCRY_NAME}/backup/taos.tar.gz -C /var/lib
    restarttaosd
    sleep 5
  fi

  if [[ "$QUICK_STYLE" != "true" ]]
  then
    target_count=`taos -hlocalhost -s "use apex_power ; select count(1) from tb_point_data;" |  grep -A 2 -E '^\s*count' | sed -n '3p' | awk '{print $1}'`

    if [[ "$source_count" -eq "$target_count" ]]
    then
      echo -e "\033[42;37m upgrade tdengines successful ... ... ...\033[0m"
    fi
  else
      echo -e "\033[42;37m fast mode will not check tdengine data count ... ... ...\033[0m"
  fi
  if [[ ! -z $encry_flag ]]
  then
    ypstart -r 1 uip
  else
    echo -e "\033[31m uip jar is not encrypted and refuses to restart \033[0m" >&2
  fi
}
common_install_new_tdengine(){
  if [[ "${sub_folder}" == "/docker" ]]
  then
    docker_install_new_tdengine
    return
  fi
  file_name=`ls ${DIR}${sub_folder} | grep -i "tdengine-server.*tar.gz" | head -n 1 | awk '{print $NF}'`
  rm -rf ${HOME}/zxhtom/tdengine_source/*
  tar -zxvf ${DIR}${sub_folder}/${file_name} -C ${HOME}/zxhtom/tdengine_source --strip-components=1
  cd ${HOME}/zxhtom/tdengine_source
  sudo sh install.sh -e no
  cd -
}
tool_install_new_tdengine(){
  tool_file_name=`ls ${DIR}/tool| grep -i "taostool.*tar.gz" | head -n 1 | awk '{print $NF}'`
  if [[ ! -d ${HOME}/zxhtom/tdengine_tool ]]
  then
    mkdir -p ${HOME}/zxhtom/tdengine_tool
  fi
  rm -rf ${HOME}/zxhtom/tdengine_tool/*
  tar -zxvf ${DIR}/tool/${tool_file_name} -C ${HOME}/zxhtom/tdengine_tool --strip-components=1
  cd ${HOME}/zxhtom/tdengine_tool
  sudo sh install-tools.sh -e no
  cd -
}
client_install_new_tdengine(){
  client_file_name=`ls ${DIR}/client | grep -i "tdengine-client.*tar.gz" | head -n 1 | awk '{print $NF}'`
  if [[ ! -d ${HOME}/zxhtom/tdengine_client ]]
  then
    mkdir -p ${HOME}/zxhtom/tdengine_client
  fi
  rm -rf ${HOME}/zxhtom/tdengine_client/*
  tar -zxvf ${DIR}/client/${client_file_name} -C ${HOME}/zxhtom/tdengine_client --strip-components=1
  cd ${HOME}/zxhtom/tdengine_client
  sudo sh install_client.sh -e no
  cd -
}
docker_install_new_tdengine(){
  if [[ ! -d /var/log/dtaos ]]
  then
    sudo mkdir -p /var/logs/dtaos
  fi
  sudo rm -rf /var/lib/taos 2>/dev/null
  if [[ ! -d /var/lib/taos ]]
  then
    sudo mkdir -p /var/lib/taos
  fi
  container_name="tdengine"
  sh ${DIR}/docker.sh
  echo ----
  sudo docker load -i ${DIR}/docker/tdengine_3.2.2.0.tar.gz
  sudo docker run -d --restart=always \
    -e TZ=Asia/Shanghai \
    --name ${container_name} -h tdengine \
    -p 6041:6041 \
    -p 6030-6035:6030-6035 \
    -p 6030-6035:6030-6035/udp \
    -v /var/log/dtaos:/var/log/taos \
    -v /var/lib/taos:/var/lib/taos \
    tdengine/tdengine:3.2.2.0
  cat /etc/hosts | grep -E '^\s*127.0.0.1\s+tdengine'
  if [[ $? -eq 1 ]]
  then
    sed -i '$a\127.0.0.1  tdengine' /etc/hosts
  fi
  commands=("rmtaos.sh" "set_core.sh" "taos" "taosadapter" "taosBenchmark" "taosd" "taosdump" "taosdemo" "taoskeeper" "TDinsight.sh" "udfd")  
  # commands=`sudo docker exec -it ${container_name} ls -t /usr/local/taos/bin/`
  if [[ ! -d /usr/local/taos/bin ]]
  then
    sudo mkdir -p /usr/local/taos/bin
  fi
  if [[ ! -d ${HOME}/temp/taos ]]
  then
    sudo mkdir -p ${HOME}/temp/taos
  fi
  template_command_sql="sudo docker exec -it ${container_name} /usr/local/taos/bin/{{bash}}"
  for command in ${commands[@]}
  do
    docker_command=`echo $template_command_sql | sed 's/{{bash}}/'"${command}"'/g'`
    touch ${HOME}/temp/taos/${command}
    echo ${docker_command}
    echo $docker_command>${HOME}/temp/taos/${command}
    # sudo cp ${HOME}/temp/taos/${command} /usr/local/taos/bin/
    # sudo chmod +x /usr/local/taos/bin/${command}
    # sudo ln -sf /usr/local/taos/bin/${command} /usr/bin/${command%.*}
    # cat ${HOME}/.bashrc | grep "alias ${command}="
    # if [[ $? -eq 1 ]]
    # then
    #   sed -i '$a\alias '"${command%.*}"'="'"${docker_command}"'"' ${HOME}/.bashrc
    # fi
  done
  sudo cp ${DIR}/taosd.service /etc/systemd/system/
  sudo cp ${DIR}/taosadapter.service /etc/systemd/system/
  # shopt -s expand_aliases
  # source ~/.bashrc
  # cat ~/.bashrc
  client_install_new_tdengine
  tool_install_new_tdengine
  sudo rm -rf /var/lib/taos/*
  sudo docker restart tdengine
  sudo systemctl disable taosadapter
  sudo systemctl disable taosd
  echo "------------------------taos version------------------------"
  taos --version
}
# DIR=$( dirname "$(readlink -f  ${BASH_SOURCE[0]})" )
DIR=$(cd "$(dirname "$0")";pwd)
TAOS_VERSION=`taos --version | awk '{print $2}' | head -n 1`
REMOTE_SERVER="127.0.0.1"
SYSTEM_INIT_FOLDER=${DIR}/system-init
ROLL_BACK=false
QUICK_STYLE=false
taos_command_sql=("show dnodes;","show mnodes;")

while getopts ":s:b:n:v:q:" opt
do
    case $opt in
        s)
        SYSTEM_INIT_FOLDER=$OPTARG
        echo -e "\033[40;37m 您输入的初始化脚本:$SYSTEM_INIT_FOLDER\033[0m"
        ;;
        b)
        ROLL_BACK=$OPTARG
        echo -e "\033[40;37m 您输入的控制回滚:$ROLL_BACK\033[0m"
        ;;
        n)
        ENCRY_NAME=$OPTARG
        echo -e "\033[40;37m 您输入的备份路径:$ENCRY_NAME\033[0m"
        ;;
        v)
        TAOS_VERSION=$OPTARG
        echo -e "\033[40;37m 您输入的回滚版本:$TAOS_VERSION\033[0m"
        ;;
        q)
        QUICK_STYLE=$OPTARG
        echo -e "\033[40;37m 您输入的快速方式:$TAOS_VERSION\033[0m"
        ;;
        ?)
        echo -e "\033[40;37m 未知参数,你可以这样使用 : sh upgrade.sh -s ~/zxhtom/system-init -btrue -nhello -v3.0.1.3\033[0m"
        exit 1;;
    esac
done

# valid start

# 1.backup exists
if [[ "$ROLL_BACK" == "true" && -z ${TAOS_VERSION} ]]
then
  TAOS_VERSION=`ls -1 ${DIR}/old | sed -r 's/.*(([0-9]+\.*){4,}).*/\1/g'`
fi

echo ${TAOS_VERSION}...
ENCRY_NAME=`printf ${REMOTE_SERVER}${TAOS_VERSION} | md5sum | cut -d ' ' -f1`

if [[ "$ROLL_BACK" == "true" ]]
then
  ls -1 ${HOME}/temp/taos | grep ${ENCRY_NAME}
  if [[ $? -eq 1 ]]
  then
    echo -e "\033[31m can not upgrade , not found upgrade folders \033[0m"
    exit 
  fi
fi

# 2. tdengine service active
taosd_status=`statustaosd`
if [[ "$ROLL_BACK" != "true" && "$taosd_status" != "active" ]]
then
    echo -e "\033[31m can not upgrade , not found tdengine services \033[0m"
    exit 
fi

# 3.valid version gt 2.x

program_tao_version=`taos --version | awk '{print $2}' | head -n 1`
if [[ "${program_tao_version%%.*}" != "3" ]]
then
    echo -e "\033[31m The current version does not support upgrades yet ... ... ... \033[0m"
    exit 
fi
# valid end
if [[ "$QUICK_STYLE" != "true" ]]
then
  source_count=`taos -hlocalhost -s "use apex_power ; select count(1) from tb_point_data;" |  grep -A 2 -E '^\s*count' | sed -n '3p' | awk '{print $1}'`
  status=`taos -h${REMOTE_SERVER} -s"show dnodes;" | awk -F '|' '{print $5}' | grep -v "^$" | sed -n '2p' | sed 's/^\s*//'`
  if [[ "$status" == ready* ]]
  then
    echo "end..."${status}
  fi

  role_status=`taos -h${REMOTE_SERVER} -s"show mnodes;" | awk -F '|' '{print $3}' | grep -v "^$" | sed -n '2p' | sed 's/^\s*//'`
  if [[ "$role_status" == leader* ]]
  then
    echo "end..."${role_status}
  fi
fi
if [[ ! -d ${HOME}/temp/taos/${ENCRY_NAME}/data ]]
then
  mkdir -p ${HOME}/temp/taos/${ENCRY_NAME}/data
fi

if [[ ! -d ${HOME}/temp/taos/${ENCRY_NAME}/backup ]]
then
  mkdir -p ${HOME}/temp/taos/${ENCRY_NAME}/backup
fi

if [[ ! -d ${HOME}/zxhtom/tdengine_source ]]
then
  mkdir -p ${HOME}/zxhtom/tdengine_source
fi
drivers_name=`ls -1 ${DIR}/drivers`
for element in ${drivers_name[@]}
do

  rpm -qa | grep ${drivers_name%.rpm}
  if [[ $? -eq 1 ]]
  then
    echo "installing ${element}" 
    sudo rpm -ivh ${DIR}/drivers/${element}
  fi
done
encry_flag=`ps -ef | grep uip | grep -v grep | grep '22HJlb4e0bacEkbP2E8nh8tgwBMrQGgJQQlB1yifFA8='`
ps -ef | grep uip | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null 

if [[ "$QUICK_STYLE" != "true" ]]
then
  second_count=`taos -hlocalhost -s "use apex_power ; select count(1) from tb_point_data;" |  grep -A 2 -E '^\s*count' | sed -n '3p' | awk '{print $1}'`
  i=0
  sleep 1
  while [[ $i -le 10 ]]
  do
    last_second_count=`taos -hlocalhost -s "use apex_power ; select count(1) from tb_point_data;" |  grep -A 2 -E '^\s*count' | sed -n '3p' | awk '{print $1}'`
    if [[ "$source_count" -eq "$last_second_count" ]]
    then
      i=10
    fi
    sleep 1
    source_count=$last_second_count
    let i++
    echo -e "\033[42;37m wait data syn finished . waitting ... waitting ... waitting ... $i\033[0m"
  done
fi
# disable update data
stoptaosadapter
if [[ `ls -al ${HOME}/temp/taos/${ENCRY_NAME}/data | wc -l` -gt 1 ]]
then
  if [[ ! -f ${HOME}/temp/taos/${ENCRY_NAME}/backup/first_record.tar.gz && -d ${HOME}/temp/taos/${ENCRY_NAME}/data ]]
  then
    tar -zcvf ${HOME}/temp/taos/${ENCRY_NAME}/backup/first_record.tar.gz -C${HOME}/temp/taos/${ENCRY_NAME} data
  fi
  if [[ "$ROLL_BACK" == "false" ]]
  then
    sudo rm -rf ${HOME}/temp/taos/${ENCRY_NAME}/data/*
  fi
fi
# export data
if [[ "$ROLL_BACK" == "false" ]]
then
  sudo taosdump -c /etc/taos/taos.cfg -o ${HOME}/temp/taos/${ENCRY_NAME}/data -h${REMOTE_SERVER} -uyapai -pypkj@1234 -A  -B80 -T8
fi
# install new tdengines 
# disable taosd
stoptaosd
# backup tdengines data dir && back up configuration

if [[ ! -f ${HOME}/temp/taos/${ENCRY_NAME}/backup/taos.tar.gz ]]
then
  taos --version >> ${HOME}/temp/taos/${ENCRY_NAME}/backup/version
  tar -zcvf ${HOME}/temp/taos/${ENCRY_NAME}/backup/taos.tar.gz -C/var/lib taos
  tar -zcvf ${HOME}/temp/taos/${ENCRY_NAME}/backup/taos_user.tar.gz -C/usr/local taos
  tar -zcvf ${HOME}/temp/taos/${ENCRY_NAME}/backup/taos_logs.tar.gz -C/var/log taos
  cp -rvf  /etc/taos/taos.cfg ${HOME}/temp/taos/${ENCRY_NAME}/backup/taos.cfg
fi

#delete old taos
sudo dpkg -r tdengine 2>/dev/null
sudo rpm -e tdengine 2>/dev/null
rmtaos 2>/dev/null <<EOF
y
I confirm that I would like to delete all data, log and configuration files
EOF
sudo docker stop tdengine 2>/dev/null
sudo docker rm -f tdengine 2>/dev/null
# install new taosd
sudo rm -rf /var/lib/taos
sub_folder=""
if [[ "$ROLL_BACK" == "true" ]]
then
  sub_folder="/old"
  if [[ `ls ${DIR}/$sub_folder | wc -l ` -le 0 ]]
  then
    sub_folder="/docker"
  fi
fi
cat /etc/redhat-release | grep -i 'stream release'
if [[ $? -eq 1 || "$ROLL_BACK" == "true" ]]
then
  common_install_new_tdengine
else
  docker_env=true
  docker_install_new_tdengine
fi
echo "I will restart taos by systemd or docker... .. ."
restarttaosd
restarttaosadapter
echo "I will check database and user init... .. ."
sleep 15
check_switch_version_status
